<?php
//prt($_SERVER);
require_once 'core/Debug.php'; //System Debug...
require_once 'core/config.php';//System Config...
require_once 'core/Init.php';  //System Init...

require_once 'includes/facebook.php';
$input = array();

//GET DATA
$input['do']  	= FunctionLib::getParam('do', '');
$input['code']  = FunctionLib::getParam('code', '');
$input['money'] = FunctionLib::getParamInt('money', 0);

if($input['do'] == 'logined'){
	//redirect after login
	header("Location: http://apps.facebook.com/emmuafb/");
}

$PROVINCE = array(
    '108109945876600' => 'ha-noi',
    '108458769184495' => 'tp-ho-chi-minh',
    '111711568847056' => 'da-nang',
    '109205905763791' => 'nha-trang',
    '114668461883395' => 'hai-phong',
    '110041405685472' => 'vung-tau'
);

//Create our Application instance (replace this with your appId and secret).
$facebook = new Facebook(array(
    'appId'     => FB_API_KEY,
    'secret'    => FB_SECRET,
    'cookie'    => true
));

//Get User ID
$user = $facebook->getUser();
if($user) {
	try {
		// Proceed knowing you have a logged in user who's authenticated.
		$fbme = $facebook->api('/me'); //prt($fbme);
		$album = $facebook->api('/229545973735228/photos?limit=70');
        
        $Paging = $album['paging'];
		$album = array_values($album);
		
		tagPhoto($facebook,'229546233735202', $fbme['id']);
		
	} catch (FacebookApiException $e) {
		error_log($e);
		$user = null;
	}
	
	//Lay Coupon cho user
    $coupon = getCuponTicket($fbme); //prt($coupon);
    if($coupon['sendMail'] == 0) {
        sendCoupon($fbme['id'], $coupon, $facebook);
    }
	if($input['do'] == 'reCoupon' && $input['code'] != '' && $input['money'] > 0){
		$coupon = reCoupon($fbme, $input['code'], $input['money']);
	}
    //prt($coupon);
	
	//Muachung
	$content = json_decode(@file_get_contents(MC_GETDEALS.$PROVINCE[$fbme['location']['id']].'.json?client_id='.MC_API_KEY));
	if($content) $Deals = $content->deals; //prt($Deals);
}
else {
	$loginUrl = $facebook->getLoginUrl(array(
		'redirect_uri' => 'http://baodp.todo.vn/emfb/?do=logined',
		'scope' => 'offline_access,publish_stream,sms,email'
	));
	
	//header("Location: $loginUrl");
}

// VAR for HTML
$i = 0;

/***********************************
*	FUNCTION
************************************/
function getCuponTicket($user = 0, $bonus = 0){ //bonus: so tien thuong do mua hang lan trc
    $coupon = array();
    if($user['id'] != '') {
		$coupon = DB::fetch("SELECT * FROM ".T_TICKET." WHERE cid = '".$user['id']."' LIMIT 0,1");
		if(empty($coupon)){
			$coupon = DB::fetch("SELECT id, ticket_code FROM ".T_TICKET." WHERE item_id = 1 AND manu_id = 0 LIMIT 0,1");
            //prt($coupon);
			if($coupon){
				$valUpdate = array(
					'cid' => $user['id'],
					'name' => $user['name'],
					'email' => $user['email'],
					'phone' => (isset($user['phone']))? $user['phone'] : '',
					'item_id' => 1,
					'manu_id' => 1,
					'bonus' => $bonus,
					'sendTime' => TIME_NOW,
					'endTime' => TIME_NOW+10*24*60*60
				);
				DB::update(T_TICKET, $valUpdate, "id = ".$coupon['id']);
			}
		}
		elseif($coupon['endTime'] < TIME_NOW) {
			$valUpdate = array(
				'email' => $user['email'],
				'sendTime' => TIME_NOW,
				'endTime' => TIME_NOW+10*24*60*60
			);
			DB::update(T_TICKET, $valUpdate, "id = ".$coupon['id']);
		}
    }
    
    return $coupon;
}

function sendCoupon($user, $coupon, $facebook) {
    $mailTemplate = 
'<table cellpadding="0" cellspacing="0" border="0" width="100%" style="font-family:arial;font-size:12px;color:#000">
  <tr>
	<td width="100%" style="background:#F7F7F7" align="center">
	  <table cellpadding="0" cellspacing="0" border="0" width="595">
		<tr>
		  <td align="right" width="100%">
			<table cellpadding="0" cellspacing="0" border="0" style="margin:20px 3px 0;font-size:11px">
			  <tr>
				<td><a href="http://www.facebook.com/pages/Emmua/146061028750390" style="text-decoration:none;color:#004b91">Emmua Fanpage</a></td>
			  </tr>
			</table>
		  </td>
		</tr>
		<tr>
		  <td style="border:2px solid #D7D7D7;border-top:none;border-left:none">
			<table cellpadding="0" cellspacing="0" border="0" width="100%" style="background:#fff;border:1px solid #C7C7C7">
                <tr>
                    <th style="text-align: left; font-size: 18px; color:#2052B1; border-bottom: 1px solid #E7E7E7; padding: 10px 20px;">Emmua</th>
                </tr>
                <tr>
                    <td width="100%" style="padding:25px 20px 0;" align="left">
                      <p style="padding:5px 0 10px;margin:0;font-size:14px"><b>Kính gửi <span style="color:#025bad;font-size:18px">@name</span> !</b></p>
                      <ul style="line-height:140%;margin:10px 15px 0;padding:0">
                        <li style="list-style:square outside;color:#cb0000;padding:0 0 5px;font-size:12px">
                          <span style="color:#000">Quý khách nhận được email này do Quý khách đã đăng ký mã số phiếu trên Emmua</span>
                        </li>
                        <li style="list-style:square outside;color:#cb0000;padding:0 0 5px;font-size:12px">
                          <span style="color:#000">Sau khi sử dụng mã số để mua hàng tại cửa hàng, quý khách cần lấy mã số mua hàng tại cửa hàng để nhận thêm phần thưởng giảm thêm 5% cho lần mua tiếp theo. Bạn nhớ lấy hóa đơn để đối chiếu giá trị hàng mua khi cần thiết.</span>
                        </li>
                      </ul>
                      <p style="margin:0;padding:20px 0 15px;font-size:14px"><b>Thông tin Phiếu mua hàng như sau:</b></p>
                        <table cellpadding="0" cellspacing="0" border="0" width="100%" style="border:5px solid #c8ebfe;font-weight:bold">
                          <tr>
                            <td style="border:1px solid #e3f5ff;border-width:0 1px 1px 0;padding:12px 15px;width:130px">Mã số phiếu:</td>
                            <td style="border-bottom:1px solid #e3f5ff;padding:12px 15px;color:#005bb0">
                              <span style="color:#cb0000;font-size:18px;padding:0 50px 0 0">@coupon</span>
                              Giảm:
                              <span style="color:#cb0000;font-size:18px">@promotion</span>
                            </td>
                          </tr>
                          <tr>
                            <td valign="top" style="border:1px solid #e3f5ff;border-width:0 1px 1px 0;padding:12px 15px;width:130px">Giảm thêm:</td>
                            <td style="border-bottom:1px solid #e3f5ff;padding:12px 15px;color:#005bb0"><span style="color:#cb0000;font-size:18px">@bonus</span> đ</td>
                          </tr>
                          <tr>
                            <td valign="top" style="border:1px solid #e3f5ff;border-width:0 1px 1px 0;padding:12px 15px;width:130px">Cửa hàng:</td>
                            <td style="border-bottom:1px solid #e3f5ff;padding:12px 15px;color:#005bb0">@address</td>
                          </tr>
                          <tr>
                            <td style="border:1px solid #e3f5ff;border-width:0 1px 1px 0;padding:12px 15px;width:130px">Hạn sử dụng:</td>
                            <td style="border-bottom:1px solid #e3f5ff;padding:12px 15px;color:#005bb0">@endTime</td>
                          </tr>
                          <tr>
                            <td style="border-right:1px solid #e3f5ff;padding:12px 15px;width:130px">Tên khách hàng:</td>
                            <td style="padding:12px 15px;color:#005bb0">@name</td>
                          </tr>
                        </table>
                    </td>
                </tr>
                <tr>
                  <td style="padding:40px 0 0" align="center">
                    <table cellpadding="0" cellspacing="0" border="0">
                      <tr>
                        <td><div style="height:8px;width:50px;background:#c8ebfe"></div></td>
                        <td><div style="height:8px;width:62px;background:#b4d3e4"></div></td>
                        <td><div style="height:8px;width:76px;background:#96c8eb"></div></td>
                        <td><div style="height:8px;width:8px;background:#87b4d3"></div></td>
                        <td><div style="height:8px;width:33px;background:#02a1dc"></div></td>
                        <td><div style="height:8px;width:38px;background:#9ccfb0"></div></td>
                        <td><div style="height:8px;width:131px;background:#bad6c5"></div></td>
                        <td><div style="height:8px;width:32px;background:#e6e5c7"></div></td>
                        <td><div style="height:8px;width:28px;background:#e6b592"></div></td>
                        <td><div style="height:8px;width:28px;background:#e67776"></div></td>
                        <td><div style="height:8px;width:101px;background:#e31b65"></div></td>
                      </tr>
                      <tr>
                        <td colspan="11" align="right" style="font-size:16px;font-family:Times new roman;padding:16px 28px 23px 0;">
                          <p style="padding:0;margin:0"><i>Nhanh tay mua sắm, hưởng trọn niềm vui</i></p>
                        </td>
                      </tr>
                    </table>
                  </td>
                </tr>
			</table>
		  </td>
		</tr>
		<tr>
		  <td align="center" style="font-family:Tahoma;font-size:11px;color:#7eabc3">
			<p style="margin:0;padding:0 0 40px">&nbsp;</p>
		  </td>
		</tr>
	  </table>
	</td>
  </tr>
</table>';

	$address = 'Giang 59 Quán Thánh, gần nút giao với Cửa Bắc';
	
	$to      = $coupon["email"];
	$subject = 'Phiếu giảm giá Emmua';
	$message = str_replace( array ('@name', '@coupon', '@promotion', '@address', '@endTime', '@bonus' ), array ($coupon['name'], $coupon['ticket_code'], "10%", $address, FunctionLib::dateFormat($coupon['endTime']), $coupon['bonus']), $mailTemplate );
	
	# send Facebook mail
	$api_call = array(
		'method' 		=> 	'notifications.sendEmail',
		'recipients'	=>	$user,
		'subject'		=>	$subject,
		'fbml'			=>	$message
	);
	
	try {
		$facebook->api($api_call);
		# cap nhat da gui coupon
		DB::update(T_TICKET, array('sendMail' => 1), "id=".$coupon['id']);
	}
	catch (FacebookApiException $e) {
		error_log($e);
		$user = null;
	}
	
	
}

function reCoupon($user, $approved_code, $money_confirm) {
	$coupon = DB::fetch("SELECT * FROM ".T_TICKET." WHERE cid = ".$user['id']." AND approved_code = '$approved_code' AND ticket_value = $money_confirm LIMIT 0,1");
	if($coupon) {
		DB::update(T_TICKET, array('money_confirm' => $money_confirm), "cid='".$user['id']."' AND approved_code = $approved_code");
		DB::delete(T_TICKET, "cid='".$user['id']."' AND approved_code = $approved_code");
		DB::insert(T_TICKET_ARCHIVE, $coupon);
		$bonus = 0;
		if($money_confirm == $coupon['ticket_value']) {
			$bonus = ($money_confirm*50);
		}
		return getCuponTicket($user, $bonus);
	}
	else {
		return false;
	}
}

function tagPhoto($fb, $photoID, $userID) {
	# send Facebook mail
	$api_call = array(
		'method' 		=> 	'photos.addTag',
		'pid'			=>	$photoID,
		'tag_uid'		=>	$userID,
		'owner_uid'		=>	'146061028750390',
		'x'				=> 	50,
		'y'				=> 	50
	);
	
	try {
		$fb->api($api_call);
	}
	catch (FacebookApiException $e) {
		error_log($e);
		$user = null;
	}
}
/***********************************
*	HTML
************************************/
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<HTML xmlns="http://www.w3.org/1999/xhtml" xmlns:fb="http://www.facebook.com/2008/fbml" xmlns:og="http://opengraphprotocol.org/schema/">
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
	<meta property="fb:admins" content="1311054854" />
	
	<!-- Framework CSS -->
	<link rel="stylesheet" href="design/css/screen.css" type="text/css" media="screen, projection">
	<link rel="stylesheet" href="design/css/print.css" type="text/css" media="print">
	<!--[if lt IE 8]><link rel="stylesheet" href="design/css/ie.css" type="text/css" media="screen, projection"><![endif]-->
	<style type="text/css" media="screen">
		p, table, hr, .box { margin-bottom:25px; }
		.box p { margin-bottom:10px; }
        .btn_next{line-height:20px;height:20px;border:1px solid #C9D2E0;display:block;margin:15px 0;padding:10px;background-color:#D8DFEA}
        .btn_next a:hover{background-color:#9eaec7}
	</style>
	<link rel="stylesheet" href="design/css/style.css" type="text/css">
	<link rel="shortcut icon" type="image/ico" href="./design/images/g.ico" />
		
	<script type="text/javascript" src="http://connect.facebook.net/en_US/all.js"></script>
	<script type="text/javascript">
		<? if(!$user) {?>
			top.location.href = "<?=$loginUrl?>";
		<? }//if ?>
	
        function framesetsize(w,h){
            var obj =   new Object;
            obj.width=w;
            obj.height=document.body.scrollHeight;
            FB.Canvas.setSize(obj);
        }
    </script>
    
	<title>Emmua - Lấy phiếu giảm MIỄN PHÍ để mua hàng</title>
</head>
<body onload="framesetsize(500,2500)">
<div id="fb-root"></div>
<? if($user) { ?>
<div class="border_corner">
	<DIV class="header">
		<div class="top">
			<div style="float:left;margin:10px"><a href="http://www.facebook.com/pages/Emmua/146061028750390" alt="Ghé thăm" target="_blank"><img src="design/images/Emmua_logo.gif" width="105px" /></a></div>
			<div style="float:left;">
				<div class="blast">
					<div style="color:green;margin-top:9px">Thời trang phụ nữ và trẻ em</div>
					<div style="color:#cb0000">Cửa hàng: Giang 59 Quán Thánh, gần nút giao với Cửa Bắc</div>
				</div>
			</div>
			<div class="clear"></div>
		</div>
	</DIV>
	
	<div class="container">
		<div class="span-19">
			<div class="span-15">
				<div class="span-9 colboder cateTitle">
					<div style="float: left; width: 100px; text-align: right;">
						<a href="<?=$fbme['link']?>" target="_blank"><img src="https://graph.facebook.com/<?=$fbme['id']?>/picture"/></a>
						<div class="fbName" style="font-size: 11px;margin-top:5px"><a href="<?=$fbme['link']?>" target="_blank"><?=$fbme['name']?></a></div>
					</div>
					<div style="float: left; margin: 0pt 0pt 0pt 10px; width: 240px;">
                        <div style="font-size:12px; font-weight:bold">Lấy ngay Coupon giảm giá <span style="font-weight:bold;color:red;font-size:14px">10%</span></div>
                        <div style="margin-top:10px; font-size:12px;">Khi mua hàng, bạn nhớ mang mã số Coupon dưới đây để được giảm giá bạn nhé</div>
                        <? if(!empty($coupon)) {?>
                          <div style="margin-top:20px;"><b>Mã số phiếu:</b> <span style="color:#cb0000;font-size:20px;padding:0 0 0 35px"><?=$coupon['ticket_code']?></span></div>
                        <? }//if ?>
					</div>
				</div>
				<div class="span-5 last cateTitle">
                    <? if(empty($coupon)) {?>
					<div>Có 56 bạn đã dùng Coupon</div>
					<!-- Friend same result -->
					<div style="width:60px;float:left;">
						<a href="#"><img src="design/images/nolayout/50102_1659468825_3698_q.jpg" class="fbImage"/></a><br/>
						<span><a href="#">Chym Chỷm Chỳm Chym</a></span>
					</div>
                    <? } else {?>
					<form name="frmReCoupon" id="frmReCoupon"  method="post">
						<input name="do" type="hidden" value="reCoupon" />
						<div>
							<div class="fl" style="float:left;width:85px">
								<div><b>Mã mua hàng</b></div>
								<div><input name="code" type="textbox" value="" style="width:70px" maxlength="3"/></div>
							</div>
							<div class="fl" style="float:left;width:105px">
								<div><b>Giá trị hàng</b></div>
								<div><input name="money" type="textbox" value="" style="width:65px" maxlength="4"/>.000đ</div>
							</div>
							<div style="clear:both"></div>
						</div>
						<div style="margin-top:10px"><input type="submit" class="inputsubmit" value="Lấy Coupon Mới"/></div>
					</form>
						<? if($coupon['sendMail'] == 1 && $input['do'] == 'reCoupon') {?>
						<div style="margin-top:10px;color:red">Giá trị bạn nhập không đúng</div>
						<? }//if ?>
                    <? }//if ?>

				</div>
				<div class="clear"></div>
				<div class="span-1">&nbsp;</div><div class="span-14 last middle">&nbsp;</div>
				
				<div class="span-15 last rightline">
					<div class="span-15 last">
						<!-- Friends Card -->
						<div class="span-1 right">&nbsp</div>
						<div class="span-14 last cateQuote2">
                            <? foreach($album[0] as $photo) {
							
							//echo $photo['id'];
                            $i++;
                            ?>
							<div class="boxPhoto">
                                <div><a href="<?=$photo['link']?>" target="_blank"><img src="<?=$photo['picture']?>" width="150px"/></a></div>
                                <? if (isset($photo['name'])) { ?>
                                <div style="margin-top:5px">Giá: <?=$photo['name']?></div>
                                <? } //if ?>
							</div>
                                <? if($i%3 == 0) {?>
                                    <div class="clear"></div>
                                <?} //if
                            }//foreach ?>
						</div>
						<div class="clear"></div>
                        <div class="span-1">&nbsp;</div>
                        <div class="span-13 last">
                            <a class="btn_next" href="<?=$Paging['next']?>">Xem tiếp</a>
                        </div>
                        <div id="end_paging"></div>
					</div>
				</div>
			</div>
			
			<!-- Quảng cáo -->
			<div class="span-4 last" style="margin:-65px 0 0 0">
				<div id="sidebar_ads">
					<div class="adcolumn">
						<div class="adcolumn_header" id="adcolumn_advertise">
							<a href="#">Emmua giới thiệu</a>
						</div>
                        <? if(isset($Deals)) {
                            foreach($Deals as $Deal) { ?>
                            <div class="more_ads" id="adcolumn_advertise">
                                <div class="title"><a href="<?=$Deal->webLink?>?from=emmua" target="_blank"><?=$Deal->shortTitle?></a></div>
								<div style="margin-bottom:5px;color:#D7D7D7">muachung.vn</div>
                                <div style="margin-bottom:5px">
                                    <a href="<?=$Deal->webLink?>?from=emmua" target="_blank"><img src="<?=$Deal->mediumImage?>"/></a>
                                </div>
                                <div>Giá: <strike><?=$Deal->options[0]->value->formattedAmount?></strike></div>
                                <div>Chỉ còn: <b><?=$Deal->options[0]->price->formattedAmount?></b></div>
                                <div>Giảm: <b style="color:red"><?=$Deal->discountPercent?> %</b></div>
                            </div>
                            <? }//foreach ?>
                        <? }//ìf ?>
					</div>
				</div>
			</div>
			
		</div>

		<div class="span-4 last"></div>
	</div>
	
	<div class="bottom"></div>
</div>

<DIV class="footer">
	<DIV class="content">
		<DIV class="copyright">Emmua © 2011</DIV>
	</DIV>
</DIV>
<? }//ìf user?>
</body>
</html>